package ift605.EquationWithTrainingAgents.behavior.reception;

import java.util.List;

import udes.ds.agent.SummativeEquation;

import ift605.EquationWithAgent.server.EquationMessage;
import ift605.EquationWithTrainingAgents.agent.PoolAgent;
import ift605.EquationWithTrainingAgents.behavior.common.ReceiveDerivativeBehavior;
import ift605.EquationWithTrainingAgents.struct.DerivationInfo;
import ift605.EquationWithTrainingAgents.struct.PendingRequest;

public class SumRebuildReceiveBehavior extends ReceiveDerivativeBehavior {
	private static final long serialVersionUID = 1L;

	@Override
	public boolean applyDerivative(EquationMessage aEquationMessage, DerivationInfo aDerivationInfo) {
		
		PoolAgent casted = ((PoolAgent)myAgent);
		
		List<PendingRequest> pendings = casted.mEquationChunk.get(aDerivationInfo.Mess.requestID);
		boolean hasAllPart = true;

		for(PendingRequest req : pendings)
		{
			if(!req.ended)
			{
				hasAllPart = false;
				break;
			}
		}
		
		if(hasAllPart)
		{
			if(pendings.size() == 1)
			{
				aDerivationInfo.Mess.derived = pendings.get(0).derived;
			}
			else
			{
				aDerivationInfo.Mess.derived = new SummativeEquation(pendings.get(0).derived,pendings.get(1).derived);
				
				for(int i = 2; i < pendings.size(); ++i)
				{
					aDerivationInfo.Mess.derived = new SummativeEquation(aDerivationInfo.Mess.derived,pendings.get(i).derived);
				}
			}
		}
		
		return hasAllPart;
	}
}
